//index.js
//获取应用实例
const app = getApp()

Page({
  data: {
    bgSrc: '../image/bg.jpeg',
    imgSrc: ''
  },
  onLoad: function () {
    var self = this;
    self.bgSrc = self.data.bgSrc;
  },
  choose: function () {
    let self = this;
    wx.chooseImage({
      success: function (res) {
        self.imgSrc = res.tempFilePaths[0];
        self.setData({
          imgSrc: res.tempFilePaths[0]
        })
      }
    });
  },
  save: function () {
    let self = this;
    if (!this.imgSrc) {
      wx.showToast({
        title: '请先选择图片',
        icon: 'none',
        duration: 2000
      });
      return false;
    }
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() {
              self.saveImage();
            }
          });
        } else {
          self.saveImage();
        }
      }
    });
  },
  saveImage() {
    wx.showLoading({
      title: '保存中...'
    });

    let self = this;
    const ctx = wx.createCanvasContext('myCanvas');
    ctx.drawImage(self.bgSrc, 0, 0, 375, 417);
    ctx.drawImage(self.imgSrc, 57, 44, 260, 264);
    ctx.draw(false, function (e) {
      console.log('画布成功了', e)
      // 保存到本地
      wx.canvasToTempFilePath({
        x: 0,
        y: 0,
        width: 375,
        height: 417,
        canvasId: 'myCanvas',
        success: function (res) {
          let pic = res.tempFilePath;
          wx.saveImageToPhotosAlbum({
            filePath: pic,
            success(res) {
              wx.hideLoading();
              console.log('成功', res)
              wx.showToast({
                title: '保存成功',
                icon: 'success',
                duration: 2000
              });
            }, fail: function (res) {
              console.log('失败', res)
              wx.hideLoading();
            }
          });
        },
        fail: function (res) {
          wx.hideLoading();
          console.log('画布错误', res)
        }
      });
    });
  }
})
